<template>
  <div>
    <el-row class="iconbox">
      <!-- <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="toggleSearch()" />
        </el-tooltip> -->
      <el-tooltip
        v-show="showOptArr.indexOf('refresh') > -1"
        class="item"
        effect="dark"
        content="刷新"
        placement="top"
      >
        <i class="el-icon-refresh-right" @click="refresh()" />
      </el-tooltip>
      <el-tooltip
        class="item"
        v-show="showOptArr.indexOf('importFile') > -1"
        effect="dark"
        content="导入"
        placement="top"
      >
        <i class="el-icon-upload2" @click="openImportOrExport('import')" />
      </el-tooltip>
      <el-tooltip
        class="item"
        v-show="showOptArr.indexOf('exportFile') > -1"
        effect="dark"
        content="导出"
        placement="top"
      >
        <i class="el-icon-download" @click="openImportOrExport('export')" />
      </el-tooltip>
      <el-tooltip
        v-if="columns"
        v-show="showOptArr.indexOf('showColumn') > -1"
        class="item"
        effect="dark"
        content="列设置"
        placement="top"
      >
        <i class="el-icon-setting" @click="showColumn()" />
      </el-tooltip>
      <el-tooltip
        v-show="showOptArr.indexOf('fullScreen') > -1"
        class="item"
        effect="dark"
        :content="showSearch ? '全屏' : '取消全屏'"
        placement="top"
      >
        <svg-icon
          v-if="!screenflag"
          icon-class="full-screen"
          @click="handleFullScreenClick()"
        />
        <svg-icon
          v-else
          icon-class="quanjusuoxiao"
          @click="handleFullScreenClick()"
        />
      </el-tooltip>
    </el-row>
    <el-drawer
      lock-scroll
      :modal-append-to-body="false"
      append-to-body
      class="avue-dialog"
      :title="this.title"
      :visible.sync="open"
    >
      <!-- @opened="init" -->
      <el-table
        :key="Math.random()"
        :data="columns"
        size="small"
        border
        class="columnTable"
        ref="columnTableRef"
        :header-cell-style="{ background: '#F2F6FC' }"
      >
        <el-table-column
          align="center"
          width="50"
          header-align="center"
          type="index"
          label="#"
          key="1"
        />
        <el-table-column
          align="center"
          width="100"
          header-align="center"
          prop="label"
          :label="'列字段'"
          key="2"
        />
        <template v-if="this.type == 'set'">
          <template v-for="item in defaultColumn">
            <el-table-column
              v-if="item.hide != true"
              :key="item.prop"
              :prop="item.prop"
              align="center"
              header-align="center"
              :label="item.label"
            >
              <template slot-scope="{ row }">
                <el-checkbox v-model="objectOption[row.prop][item.prop]" />
              </template>
            </el-table-column>
          </template>
        </template>
        <template v-if="this.type == 'import'">
          <template v-for="item in importColumn">
            <el-table-column
              v-if="item.hide != true"
              :key="item.prop"
              :prop="item.prop"
              align="center"
              header-align="center"
              :label="item.label"
            >
            <template slot-scope="{ row }">
                <el-checkbox :disabled="objectOption[row.prop][item.isImport]"  v-model="objectOption[row.prop][item.prop]"/>
              </template>
            </el-table-column>
          </template>
        </template>
        <template v-if="this.type == 'export'">
          <template v-for="item in exportColumn">
            <el-table-column
              v-if="item.hide != true"
              :key="item.prop"
              :prop="item.prop"
              align="center"
              header-align="center"
              :label="item.label"
            >
              <template slot-scope="{ row }">
                <el-checkbox  v-model="objectOption[row.prop][item.prop]" />
              </template>
            </el-table-column>
          </template>
        </template>
      </el-table>

      <div class="columnTable" style="margin-top: 15px">
        <el-button
          size="mini"
          v-if="this.type == 'import'"
          type="primary"
          @click="exportTemplate()"
          >下载数据模板</el-button
        >
        <el-upload 
          style="display: inline-block;margin-left: 20px;"
          v-if="this.type === 'import'"
          v-loading="uploading"
          :action="uploadURL"
          :headers="uploadHeaders"
          :before-upload="onBeforeUpload"
          :on-success="onSuccess"
          :on-error="onError"
          :show-file-list="false"
          :limit="1"
        >
          <el-button
            size="mini"
            type="primary"
          >导入数据(最大可导入10M的文件)</el-button>
        </el-upload>
        <el-button
          size="mini"
          v-if="this.type == 'export'"
          type="primary"
          @click="exportExcel('0')"
          >导出全部数据</el-button
        >
        <el-button
          size="mini"
          v-if="this.type == 'export'"
          type="primary"
          @click="exportExcel('1')"
          >导出选中数据</el-button
        >
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {
  getTemplate,
  importData as importAPI,
  exportData,
  exportSelectedData,
} from "@/framework/components/dialog-column/importExport";
import { cloud } from '@/framework/utils/request'
import { getToken } from '@/framework/utils/auth'
export default {
  name: "DialogColumn",
  inject: {
    showOptArr: {
      // 处理显示几个按钮
      default: () => {
        return [
          "refresh",
          "importFile",
          "exportFile",
          "showColumn",
          "fullScreen",
        ];
      },
    },
  },
  props: {
    value: [Boolean],
    showSearch: {
      type: Boolean,
      default: true,
    },
    columns: {
      type: Array,
      default: () => {
        return [];
      },
    },
    tableRef: {
      type: [Array, Object],
      default: () => {
        return {};
      },
    },
    query: {
      type: Object,
      default: () => ({ url: '', params: undefined, method: 'get' }),
      validator: val => {
        const keys = Object.keys(val)
        const required = ['url', 'params', 'method']
        return required.every(prop => keys.includes(prop))
      }
    },
  },
  data() {
    return {
      uploading: false,
      loading: false,
      open: false,
      bindList: {},
      list: [],
      objectOption: {},
      screenflag: false,
      title: "",
      type: "set",
      columnInfos: [],
    };
  },
  computed: {
    defaultColumn() {
      return [
        {
          label: "显示",
          prop: "show",
        },
        {
          label: "固定",
          prop: "fixed",
        },
        {
          label: "排序",
          prop: "sortable",
        }
      ];
    },
    importColumn() {
      return [
        {
          label: "是否导入",
          prop: "template",
          isImport: "isImport",
        }
      ];
    },
    exportColumn() {
      return [
        {
          label: "是否导出",
          prop: "template",
        },
      ];
    },
    baseURL() {
      return process.env.VUE_APP_BASE_API + cloud.file
    },
    uploadHeaders() {
      return {
        Authorization: getToken()
      }
    },
    uploadURL() {
      return this.baseURL + '/sysFileInfo/upload?secretFlag=N'
    },
  },
  watch: {
    value: {
      handler: function (newVal, oldVa) {
        // this.show = newVal
      },
      immediate: true,
      deep: true,
    },
    open: {
      handler(val) {
        if (val) {
          let list = this.columns;
          this.objectOption = {};
          list.forEach((ele) => {
            this.objectOption[ele.prop] = ele
          });
        }
      },
      deep: true,
    },
    columns: {
      handler(newValue, oldValue) {
        this.$nextTick(() => {
          this.tableRef.doLayout();
        });
      },
      deep: true,
    },
  },
  methods: {
    // 表格数据处理
    dealColums() {
      this.columnInfos=[];
      var i=1;
      this.columns.forEach((item,index)=>{
        console.info("item= ", item);
        if(item.template == true){
          var fileColumn={
            'columnNo': i,
            'columnName': item.label,
            'columnMapping': item.prop,
            'isImport': item.isImport,
            'templateValue': item.templateValue,
            'dictTypeCode': item.dictTypeCode
          }
          this.columnInfos.push(fileColumn);
          i++;
        }
      })
    },
    exportTemplate() {
      this.loading=true;
      this.dealColums();
      getTemplate(this.columnInfos).then(({ data: fileId }) => {
        this.loading=false;
        this.download(fileId);
      });
    },
    onBeforeUpload(file) {
      const maximum = 10 * 1024 * 1024
      const fileExt = file.name.split('.').reverse()[0]
      const exts = ['xls', 'xlsx']

      this.uploading = true

      if (!exts.includes(fileExt)) {
        this.$message.error(`请上传后缀为${exts.join('/')}的文件`)
        return false
      }

      if (file.size > maximum) {
        this.$message.error('您上传文件超过系统限制的最大值，最大可上传10M的文件!')
        return false
      }
      this.dealColums();
      return true
    },
    onSuccess(resp) {
      importAPI({
        file: resp.data.fileId,
        menu: this.query.menu,
        columns: this.columnInfos
      }).then(res => {
        if (res.success) {
          this.$message.success("导入成功")
        }
      }).finally(() => {
        this.uploading = false
      })
    },
    onError(err) {
      this.$message.error(err)
      this.uploading = false
    },
    exportExcel(type) {
      this.dealColums();
      var request={
          type: '0',
          url: this.query.url,
          params: this.query.params,
          method: this.query.method,
          columns: this.columnInfos
        };
      this.$emit('exportStart')
      if(type == '1'){
        request.type='1';
        request.idList=this.query.selection;
        request.idProp=this.query.idProp;
        request.idList=this.query.selection;
        request.idList=this.query.selection;
        exportSelectedData(request).then((res) => {
          this.download(res.data)
        }).catch(() => {
          this.$emit('exportStart', true)
        })
        return
      }
      exportData(request).then((res) => {
        this.download(res.data)
      }).catch(() => [
        this.$emit('exportStart', true)
      ])
    },
    //下载文件
    download(fileId) {
      const hasToken = getToken()
      let url =`${this.baseURL}` 
      url += '/sysFileInfo/publicDownload?fileId=' + fileId  + '&token=' + hasToken
      window.location.href = url
      this.$emit('exportStart', true)
    },
    openImportOrExport(val) {
      this.open = true;
      if(val == 'import'){
        this.title = "导入信息";
        this.type = "import";
      }else{
        this.title = "导出信息";
        this.type = "export";
      }
    },

    // 搜索
    toggleSearch() {
      this.$emit("update:showSearch", !this.showSearch);
    },
    // 刷新
    refresh() {
      this.$emit("queryTable");
    },
    // 打开显隐列dialog
    showColumn() {
      this.open = true;
      this.title = "列设置";
      this.type = "set";
      // this.dealDialogColumnData()
    },
    handleFullScreenClick() {
      this.screenflag = !this.screenflag;
      if (this.$parent.$el.className.indexOf("table-fullscreen") > -1) {
        if (this.$parent.$el.className.indexOf("ele-table-fullscreen") > -1) {
          this.$parent.$el.classList.remove("ele-table-fullscreen");
        } else {
          this.$parent.$el.classList.add("ele-table-fullscreen");
        }
      } else {
        if (
          this.$parent.$el.getElementsByClassName("ele-table-fullscreen")[0]
        ) {
          this.$parent.$el
            .getElementsByClassName("table-fullscreen")[0]
            .classList.remove("ele-table-fullscreen");
        } else {
          this.$parent.$el
            .getElementsByClassName("table-fullscreen")[0]
            .classList.add("ele-table-fullscreen");
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.columnTable {
  width: 93%;
  margin: 0 auto;
  border-left: 1px solid #dfe6ec !important;
}
</style>
